<template>
  <el-dialog :close-on-click-modal="false" :title="form.id ? $t('common.editBtn') : $t('common.addBtn')" width="600"
             draggable v-model="gradeVisible">
    <el-form :model="form" :rules="dataRules" label-width="90px" ref="dataFormRef" v-loading="loading">
      <el-form-item label="年级名称" prop="gradeName">
        <el-input placeholder="请输入年级名称" clearable v-model="form.gradeName"></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sortd">
        <el-input-number v-model="form.sortd" :min="0" controls-position="right"/>
      </el-form-item>
    </el-form>
    <template #footer>
			<span class="dialog-footer">
				<el-button @click="gradeVisible = false">{{ $t('common.cancelButtonText') }}</el-button>
				<el-button @click="onSubmit" type="primary" :disabled="loading">{{ $t('common.confirmButtonText') }}</el-button>
			</span>
    </template>
  </el-dialog>
</template>

<script lang="ts" name="systemRoleDialog" setup>
import {useMessage} from '/src/hooks/message';
import {addObj, getObj, putObj } from '/src/api/school/grade';
import {useI18n} from 'vue-i18n';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

const {t} = useI18n();

// 定义变量内容
const dataFormRef = ref();
const gradeVisible = ref(false);
const loading = ref(false);

// 提交表单数据
const form = reactive({
  id: '',
  gradeName: '',
  schoolId: '',
  sortd: null
});

// 定义校验规则
const dataRules = ref({
  gradeName: [
    {required: true, message: '年级名称不能为空', trigger: 'blur'},
    {max: 50, message: '长度在 50 个字符内', trigger: 'blur'},
  ],
  sortd: [
    {required: true, message: '排序不能为空', trigger: 'blur'},
  ],
});

// 打开弹窗
const openDialog = (schoolId: string , id: string) => {
  gradeVisible.value = true;
  form.id = '';
  form.schoolId = schoolId;
  nextTick(() => {
    dataFormRef.value.resetFields();
  });

  // 获取角色信息
  if (id) {
    form.id = id;
    getRoleData(id);
  }

};

// 初始化数据
const getRoleData = (id: string) => {
  // 获取部门数据
  getObj(id).then((res: any) => {
    Object.assign(form, res.data);
  });
};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {
  });
  if (!valid) return false;

  try {
    loading.value = true;
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(t(form.id ? 'common.editSuccessText' : 'common.addSuccessText'));
    gradeVisible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};





// 暴露变量
defineExpose({
  openDialog,
});
</script>
